<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报表类型" prop="reportType">
        <el-select v-model="queryParams.reportType" placeholder="请选择报表类型" clearable>
          <el-option label="日报" value="1" />
          <el-option label="周报" value="2" />
          <el-option label="月报" value="3" />
          <el-option label="年报" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="统计日期">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['energy:report:add']"
        >生成报表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['energy:report:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-data-analysis"
          size="mini"
          @click="showAnalysisDialog = true"
        >数据分析</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card class="box-card">
          <div class="stat-card">
            <div class="stat-icon" style="background: #409EFF;">
              <i class="el-icon-lightning"></i>
            </div>
            <div class="stat-content">
              <p class="stat-value">{{ (dashboardStats.todayStats && dashboardStats.todayStats.totalEnergy) || 0 }}</p>
              <p class="stat-label">今日总能耗(kWh)</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div class="stat-card">
            <div class="stat-icon" style="background: #67C23A;">
              <i class="el-icon-cpu"></i>
            </div>
            <div class="stat-content">
              <p class="stat-value">{{ (dashboardStats.todayStats && dashboardStats.todayStats.avgPower) || 0 }}</p>
              <p class="stat-label">平均功率(kW)</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div class="stat-card">
            <div class="stat-icon" style="background: #E6A23C;">
              <i class="el-icon-money"></i>
            </div>
            <div class="stat-content">
              <p class="stat-value">{{ (dashboardStats.todayStats && dashboardStats.todayStats.totalCost) || 0 }}</p>
              <p class="stat-label">能耗成本(元)</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div class="stat-card">
            <div class="stat-icon" style="background: #F56C6C;">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stat-content">
              <p class="stat-value">{{ (dashboardStats.todayRunning && dashboardStats.todayRunning.totalFaultCount) || 0 }}</p>
              <p class="stat-label">故障次数</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="统计日期" align="center" prop="reportDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报表类型" align="center" prop="reportType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.reportType == '1'" type="primary">日报</el-tag>
          <el-tag v-else-if="scope.row.reportType == '2'" type="success">周报</el-tag>
          <el-tag v-else-if="scope.row.reportType == '3'" type="info">月报</el-tag>
          <el-tag v-else-if="scope.row.reportType == '4'" type="warning">年报</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总能耗(kWh)" align="center" prop="totalEnergy" />
      <el-table-column label="平均功率(kW)" align="center" prop="avgPower" />
      <el-table-column label="运行时长(h)" align="center" prop="runHours" />
      <el-table-column label="能耗成本(元)" align="center" prop="energyCost" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['energy:report:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 生成报表对话框 -->
    <el-dialog title="生成报表" :visible.sync="generateDialog" width="500px" append-to-body>
      <el-form ref="generateForm" :model="generateForm" :rules="generateRules" label-width="80px">
        <el-form-item label="报表类型" prop="reportType">
          <el-select v-model="generateForm.reportType" placeholder="请选择报表类型">
            <el-option label="日报" value="1" />
            <el-option label="月报" value="3" />
            <el-option label="年报" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="统计日期" prop="reportDate">
          <el-date-picker
            v-model="generateForm.reportDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="generateDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitGenerate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReport, delReport, generateReport, getDashboardStats, exportReport } from "@/api/energy/report";

export default {
  name: "Report",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报表表格数据
      reportList: [],
      // 日期范围
      dateRange: [],
      // 仪表盘数据
      dashboardStats: {},
      // 生成报表对话框
      generateDialog: false,
      // 分析对话框
      showAnalysisDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        reportType: null
      },
      // 生成报表表单
      generateForm: {
        reportType: null,
        reportDate: null
      },
      // 生成报表表单校验
      generateRules: {
        reportType: [
          { required: true, message: "报表类型不能为空", trigger: "change" }
        ],
        reportDate: [
          { required: true, message: "统计日期不能为空", trigger: "blur" }
        ]
      },
      // 报表类型选项
      reportTypeOptions: [
        { label: "日报", value: "1" },
        { label: "周报", value: "2" },
        { label: "月报", value: "3" },
        { label: "年报", value: "4" }
      ]
    };
  },
  created() {
    this.getList();
    this.getDashboard();
  },
  methods: {
    /** 查询报表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.dateRange && '' != this.dateRange) {
        this.queryParams.params["beginTime"] = this.dateRange[0];
        this.queryParams.params["endTime"] = this.dateRange[1];
      }
      listReport(this.queryParams).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取仪表盘数据 */
    getDashboard() {
      getDashboardStats().then(response => {
        this.dashboardStats = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.generateDialog = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reportIds = row.reportId || this.ids;
      this.$modal.confirm('是否确认删除报表编号为"' + reportIds + '"的数据项？').then(function() {
        return delReport(reportIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/energy/report/export', {
        ...this.queryParams
      }, `report_${new Date().getTime()}.xlsx`);
    },
    /** 提交生成报表 */
    submitGenerate() {
      this.$refs["generateForm"].validate(valid => {
        if (valid) {
          generateReport(this.generateForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.generateDialog = false;
            this.getList();
            this.getDashboard();
          });
        }
      });
    },
    /** 详情操作 */
    handleDetail(row) {
      this.$router.push('/energy/report/detail/' + row.reportId);
    }
  }
};
</script>

<style scoped>
.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 5px 0;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.box-card {
  margin-bottom: 20px;
}
</style> 